PROJECTNAME = s21_decimal
CC = gcc
CFLAGS = -Wall -Wextra -Werror -std=c11 
LFLAGS = -lcheck
GCOVFLAGS = -fprofile-arcs -ftest-coverage
OS = $(shell uname -s)
SOURCES = $(wildcard functions/*.c)
OBJECTS = $(patsubst %.c, %.o, $(SOURCES))

ifeq ($(OS), Linux)
	LFLAGS += -lm -lpthread -lrt -lsubunit
endif

%.o: %.c
	$(CC) -c $(CFLAGS) $< -o $@

all: clean format $(PROJECTNAME).a leaks gcov_report

$(PROJECTNAME).a: $(OBJECTS)
	$(info ********************  $(PROJECTNAME).a   *******************)
	ar -rcs $@ $^
	rm -rf $^

test: tests/$(PROJECTNAME)_test.c $(PROJECTNAME).a
	$(CC) $(CFLAGS) $^ -o test.out $(LFLAGS)
	./test.out

gcov_report: tests/$(PROJECTNAME)_test.o
	$(info ********************    gcov_report     ********************)
	make lcov
	$(CC) $(CFLAGS) $< $(SOURCES) -o $@ $(GCOVFLAGS) $(LFLAGS)
	./gcov_report
	lcov -d ./ --capture --output-file gcov_report.info
	genhtml gcov_report.info --output-directory report
	rm -rf *.gcno *.gcda *.gcov *.info gcov_report $<
	google-chrome ./report/index.html

lcov:
ifeq ("", "$(shell PATH=$(PATH) which lcov)")
	$(error Need to install lcov)
endif	

rebuild: all

clean:
	$(info ********************       clean        ********************)
	rm -rf functions/*.o tests/*.o *.o *.a *.out
	rm -rf ./report *.gcno *.gcda *.gcov *.info gcov_report

format:
	$(info ********************       format       ********************)
	clang-format -i -style=Google functions/*.c tests/*.c *.h

leaks: test
	$(info ********************       leaks        ********************)
	valgrind --tool=memcheck --leak-check=yes --leak-check=full --show-leak-kinds=all ./test.out
